const net = require('net');

const TCP_SERVER_HOST = '127.0.0.1'; // Netty 服务器地址
const TCP_SERVER_PORT = 7894; // Netty 服务器端口
const TOTAL_CONNECTIONS = 50000; // 模拟的总连接数
const CONNECTION_BATCH_SIZE = 100; // 每次启动的连接数
const BATCH_DELAY = 100; // 每批连接的间隔时间（毫秒）

let connectedClients = 0; // 当前已建立连接的客户端数量
let failedClients = 0; // 连接失败的客户端数量
let sockets = []; // 存储所有客户端 socket

// 启动多个客户端连接到服务器
function startClients() {
    for (let i = 1; i <= TOTAL_CONNECTIONS; i++) {
        const client = new net.Socket();

        client.connect(TCP_SERVER_PORT, TCP_SERVER_HOST, () => {
            connectedClients++;
            sockets.push(client); // 保存连接
            console.log(`Client ${i} connected. Total connected: ${connectedClients}`);
        });

        client.on('error', (err) => {
            failedClients++;
            console.error(`Client ${i} failed to connect: ${err.message}`);
        });

        client.on('close', () => {
            connectedClients--;
            console.log(`Client ${i} disconnected. Total connected: ${connectedClients}`);
        });
    }
}

// 分批启动客户端
function startClientsInBatches() {
    let currentBatch = 0;

    const interval = setInterval(() => {
        const start = currentBatch * CONNECTION_BATCH_SIZE + 1;
        const end = Math.min(start + CONNECTION_BATCH_SIZE - 1, TOTAL_CONNECTIONS);

        for (let i = start; i <= end; i++) {
            const client = new net.Socket();

            client.connect(TCP_SERVER_PORT, TCP_SERVER_HOST, () => {
                connectedClients++;
                sockets.push(client); // 保存连接
                console.log(`Client ${i} connected. Total connected: ${connectedClients}`);
            });

            client.on('error', (err) => {
                failedClients++;
                console.error(`Client ${i} failed to connect: ${err.message}`);
            });

            client.on('close', () => {
                connectedClients--;
                console.log(`Client ${i} disconnected. Total connected: ${connectedClients}`);
            });
        }

        currentBatch++;
        if (currentBatch * CONNECTION_BATCH_SIZE >= TOTAL_CONNECTIONS) {
            clearInterval(interval); // 停止批量启动
            console.log('All clients attempted to connect.');
        }
    }, BATCH_DELAY);
}

// 程序入口
function main() {
    console.log('Starting connection test...');
    startClientsInBatches();

    // 定期打印当前连接状态
    setInterval(() => {
        console.log(`Currently connected: ${connectedClients}, Failed connections: ${failedClients}`);
    }, 5000);
}

main();
